Home:ALL Converter>How can this association be set up?

How can this association be set up?

Ask Time:2012-06-22T04:31:05         Author:Nick Savage

Json Formatter

I'm using the cakephp framework to develop an application and I'm running into some trouble understanding the associations between these models fully. Below you can see the four models along with their relative database fields.

User
 id

Profile
 id
 user_id

Post (A blog post on the users profile)
 id
 profile_id
 topic_id

Topic (A topic for a blog post)
 id
 name

Here are the associations as they currently stand:

User
 hasOne: Profile

Profile
 hasMany: Posts

Post
 belongsTo: Topic, Profile

Now my problem. I am unsure if you have to define associations like User hasMany Posts or if it's already assumed because User hasOne Profile and Profile hasMany Posts. My other problem is defining the relationship between a post and its topic.

  • A profile can have unlimited posts
  • A post must be associated with a profile
  • A post can only have one topic
  • The topic table contains a list of all topics
  • A post does not NEED a topic

Given these criteria how should my associations look? All the research I've done on associations only shows simple examples.

I'm using CakePHP version 2.1.3

Thanks for any and all help and/or advice in advance

Author:Nick Savage,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/11146266/how-can-this-association-be-set-up
tyjkenn :

You can recursively find associations of associations, or even better, use Containable.\n\nIn the model (I recommend putting it in AppModel, since I find myself using Containable for everything):\n\nclass AppModel extends Model {\n public $actsAs = array('Containable');\n ...\n}\n\n\nThen when you call read (or find, or paginate) for User, most likely in your controller, do this:\n\n$this->User->contain(array(\n 'Profile' => array(\n 'Post'\n )\n));\n$data = $this->User->read();\n$set('user',$data);\n\n\nIf you set that data to your view, you can then access the id of one of the posts from $user['Profile']['Post'][0]['id'].\n\nNow for your next question, you can have conditional associations.\n\npublic $hasMany = array(\n 'Topic' => array(\n 'className' => 'Topic',\n 'conditions' => 'Post.topic_id IS NOT NULL'\n )\n)\n",
2012-06-21T22:04:08
yy